<?php


namespace App\LayAdmin\Controllers;


use App\Exceptions\ExceptionApi;
use App\LayAdmin\Components\Form;
use App\LayAdmin\Components\Table;
use App\LayAdmin\Components\TableData;
use App\LayAdmin\Components\TableItemOperate;
use App\Models\AppRelease;
use App\Services\Uri;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;

class AppController extends BaseController
{

    /**
     * @throws ExceptionApi
     */
    public function createRelease(Request $request):Response{
        if($request->method()==Request::METHOD_POST){
            $data = $request->input('data');
            $model = AppRelease::create($data);
            $model->description = $data['description'];
            if($model->save()){
                return $this->successApi();
            }
            $this->errorOptFail();
        }
        $form = new Form('/admin/app/create-release');
        return $this->form($form);
    }

    protected function form(Form $form, AppRelease $model=null):Response{
        $version_name = $model ? $model->version_name : '';
        $version_code = $model ? $model->version_code : 0;
        $path = $model ? $model->path : '';
        $description = $model ? $model->description : '';
        $force_update = $model ? $model->force_update : 0;
        $state = $model ? $model->state : 1;

        $form->field('version_name', $version_name)->textInput()->label('版本名(version_name)');
        $form->field('version_code', $version_code)->textInput(['placeholder'=>'请填写整数'])->label('版本号(version_code)');
        $form->field('path', $path)->uploadInput("/admin/app/upload-package",['style'=>'width:320px'])->label('文件路径');
        $form->field('description', $description)->textarea()->label('描述');
        $form->field("force_update", $force_update)->radioList([1=>'是',0=>'否'])->label('强制更新');
        $form->field("state", $state)->radioList([1=>'是',0=>'否'])->label('是否启用');
        $form->submit();
        return new Response($form);
    }

    protected function getModel(Request $request):AppRelease{
        $id = $request->input('id');
        $model = AppRelease::find($id);
        if(empty($model)){
            $this->errorRequest('操作的对象不存在');
        }
        return $model;
    }

    public function release(Request $request):Response{
        $model = $this->getModel($request);
        if($request->method()==Request::METHOD_POST){
            foreach ($request->input('data') as $key => $value){
                if($key=='file'){
                    continue;
                }
                $model->setAttribute($key, $value);
            }
            if($model->save()){
                return $this->successApi();
            }
            $this->errorOptFail();
        }
        $form = new Form('/admin/app/release?id='.$request->input('id'));
        return $this->form($form, $model);
    }

    public function releases(Request $request):Response{
        $table = new Table("/admin/app/get-releases");
        $table->addBtnOpenByUrl("/admin/app/create-release",'添加');
        $table->field('id','ID')->setWidth(50);
        $table->field('path', '下载地址')->setMinWidth(360);
        $table->field('version_code','版本号');
        $table->field('version_name', '版本名');
        $table->field('force_update', '强制更新');
        $table->field('state', '是否启用');
        $table->field('created_at','上传时间');
        $table->itemOperate(function (TableItemOperate $operate){
            $operate->setEditBtn("\"/admin/app/release?id=\"+data.id");
        });
        return new Response($table->render());
    }

    public function getReleases(Request $request):Response{
        $page = $request->input('page',1);
        $limit = $request->input('limit',30);
        $query = AppRelease::query()->orderByDesc('created_at');

        $searchParams = $request->input('searchParams');
        if($searchParams){
            $filter = json_decode($searchParams, true);
            AppRelease::filterData($query, $filter);
        }

        $itemsPg = $query->paginate($limit, ["*"], 'page', $page);

        $items = $itemsPg->items();
        foreach ($items as &$item){
            $item['state'] = $item['state']==0 ? '否' : '是';
            $item['force_update'] = $item['force_update']==0 ? '否' : '是';
            $url = Uri::createAppUrl($item['path']);
            $item['path'] = "<a href=\"{$url}\" target='_blank'>{$item['path']}</a>";
        }
        $total = $itemsPg->total();
        $response = (new TableData($items, $total))->toArray();
        return new Response($response);
    }

    public function uploadPackage(Request $request):Response{
        $file = $request->file('file');
//        $originName = $file->getClientOriginalName();
        $originExt = $file->getClientOriginalExtension();
        $saveName = "抖个球".date('md').Str::random(3).".".$originExt;
        $path = $file->storeAs('app_releases', $saveName, 'uploads');
        return $this->successApi('上传成功',['src'=>$path]);
    }

}
